/** 
 
*/
import React, { PureComponent } from 'react';
import { DATA_ENTRY, AdvancedSearch, ContentPackage, TableC, ModalC } from '../../../../comps';
import { Checkbox, message } from 'antd';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';
import EtfProposalC from '../etfProposal';
import statusData from '../../../../utils/enumeratedValues/statusData';

class TradeSearch extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [],
      dataSource: [],
      searchObj: {},
      isReset: false, // 是否点击了重置
      proposalStatus: undefined, // 建议书状态
      proposalType: undefined, // 建议书类型
      instructionStatus: undefined, // 指令状态
      refreshChecked: true, // 是否自动刷新
      etfCode: undefined, // ETF类型的code
      detailData: undefined, // 明细数据
      detailModalVisible: false, // 明细模态框的显示隐藏
    };
  }

  componentDidMount() {
    const {
      globalM: {
        dataDictionary: { PROPOSAL_STATUS = [], PROPOSAL_TYPE = [], TRADE_BUS_STATUS = [] },
      },
    } = this.props;
    // 建议书类型
    this.props.dispatch({
      type: 'tradeSearchM/etfproposalSelect',
      payload: {
        PROPOSAL_STATUS,
        PROPOSAL_TYPE,
        TRADE_BUS_STATUS,
      },
      callback: (type, res) => {
        if (type == 'success') {
          this.setState(
            {
              proposalStatus: res.PROPOSAL_STATUS,
              proposalType: res.PROPOSAL_TYPE,
              instructionStatus: res.TRADE_BUS_STATUS,
            },
            () => {
              this.state.proposalType &&
                this.state.proposalType.forEach((item) => {
                  if (item.value == 'ETF建议书') {
                    this.setState({
                      etfCode: item.code,
                    });
                  }
                });
            },
          );
        }
      },
    });
    // 获取建议书表格数据
    this.queryTableList();
    this.timer = setInterval(() => {
      this.queryTableList();
    }, 5000);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}
  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }
  // 获取建议书表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage } = this.state;
    this.props.dispatch({
      type: 'tradeSearchM/getTradeData',
      payload: {
        ...searchObj,
        currentPage: currentPage,
        numInPage: numInPage,
      },
      callback: (type, res) => {
        if (type == 'success') {
          // 前端翻译状态，类型，指令状态
          res.dataSource &&
            res.dataSource.map((item) => {
              this.state.proposalType &&
                this.state.proposalType.map((items) => {
                  if (item.proposalType == 'ETF') {
                    item['proposalType'] = '场内(ETF)基金';
                  }
                });
              this.state.proposalStatus &&
                this.state.proposalStatus.map((itemss) => {
                  if (item.proposalStatus == itemss.value) {
                    item['proposalStatus'] = itemss.title;
                  }
                });
              this.state.instructionStatus &&
                this.state.instructionStatus.map((items) => {
                  if (item.instructionStatus == items.code) {
                    item['instructionStatus'] = items.value;
                  }
                });
              statusData.clinchStatus.map((items) => {
                if (item.clinchStatus == items.value) {
                  item['clinchStatus'] = items.title;
                }
              });
            });
          this.setState({
            columns: res.columns,
            dataSource: res.dataSource,
            total: res.pageInfo && res.pageInfo.total,
          });
        }
      },
    });
  };
  // 查询事件
  queryTableList = () => {
    const tempItem = this.addOrder.props.form.getFieldsValue();
    let params = {
      portfolioId: tempItem.portfolioId ? tempItem.portfolioId : undefined,
      proposalWriteDate: tempItem.proposalWriteDate ? tempItem.proposalWriteDate.format('YYYY-MM-DD') : undefined,
      proposalType: tempItem.proposalType ? tempItem.proposalType : 'ETF',
      proposalStatus: tempItem.proposalStatus ? tempItem.proposalStatus : undefined,
      username: tempItem.username ? tempItem.username : undefined,
    };
    this.setState(
      {
        searchObj: params,
        columns: [],
        dataSource: [],
        // currentPage: 1,
        // numInPage: 10,
        isReset: false,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 是否自动刷新
  onRefresh = (e) => {
    this.setState({
      refreshChecked: e.target.checked,
    });
    if (e.target.checked == false) {
      this.timer && clearInterval(this.timer);
    } else {
      this.timer = setInterval(() => {
        this.queryTableList();
      }, 5000);
    }
  };
  // 明细按钮点击事件
  onEditItem = (proposalId) => {
    const { proposalStatus, proposalType } = this.state;
    this.props.dispatch({
      type: 'tradeSearchM/getDetailData',
      payload: {
        proposalId: proposalId,
      },
      callback: (type, res) => {
        if (type == 'success') {
          for (let k in res) {
            if (k == 'proposalStatus') {
              proposalStatus.forEach((item) => {
                if (res[k] == item.value) {
                  res[k] = item.title;
                }
              });
            }
            if (k == 'proposalType') {
              proposalType.forEach((item) => {
                if (res[k] == item.value) {
                  res[k] = item.title;
                }
              });
            }
          }
          this.setState({
            detailData: res,
            detailModalVisible: true,
          });
        }
      },
    });
  };
  // 撤回按钮点击事件
  handleCancel = (proposalId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tradeSearchM/cancelInstruction',
      payload: {
        proposalId: proposalId,
      },
    }).then((res) => {
      if (res.success) {
        this.queryTableList();
      }
    });
  };
  // 明细确认按钮点击事件
  detailOK = () => {
    this.setState({
      detailModalVisible: false,
    });
  };
  // 明细模态框取消按钮点击事件
  detailCancel = () => {
    this.setState({
      detailModalVisible: false,
    });
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 显示存款账号信息表格
  showTable = () => {
    const { currentPage, total, numInPage, columns, dataSource } = this.state;
    //因为columns来自props，会不停的渲染添加操作列，在此做一下判断
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        title: '操作',
        width: '150px',
        operates: [
          {
            title: '明细',
            onClick: (record, index) => {
              this.onEditItem(record.proposalId);
            },
          },
          {
            title: '撤回',
            onClick: (record, index) => {
              this.handleCancel(record.proposalId);
            },
            rules: {
              disabled: {
                relation: 'and',
                items: [
                  { key: 'instructionStatus', value: ['已下达'], relation: ['!='] },
                  { key: 'instructionStatus', value: ['已执行'], relation: ['!='] },
                ],
              },
            },
          },
        ],
      });
    }
    if (columns && columns.length) {
      columns.map((item) => {
        if (item.key == 'proposalWriteDate' || item.key == 'clinchStatus' || item.key == 'proposalStatus' || item.key == 'instructionStatus') {
          item.width = 100;
        }
        if (item.key == 'proposalId') {
          item.width = 250;
        }
        if (item.key == 'proposalName' || item.key == 'productName' || item.key == 'portfolioName' || item.key == 'username' || item.key == 'verifyUsername') {
          item.width = 150;
        }
        if (item.key == 'investmentType' || item.key == 'proposalType') {
          item.width = 80;
        }
      });
    }
    return (
      <TableC
        columns={columns}
        loading={this.props.loading.effects['tradeSearchM/getTradeData'] == true}
        dataSource={dataSource}
        current={currentPage}
        total={total}
        pageSize={numInPage}
        selfScrollY={true}
        rowKey='proposalId'
        scroll={{ x: 'max-content' }}
        onChange={this.handleTableChange}
      />
    );
  };
  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'proposalWriteDate',
          title: '日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
        },
        {
          dataIndex: 'proposalType',
          title: '资产类型',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: [{ title: '场内(ETF)基金', value: 'ETF' }],
          initialValue: 'ETF',
        },
        {
          dataIndex: 'portfolioId',
          title: '组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          maatApi: true,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //不包含估值解析和估值对接的产品
        },
        {
          dataIndex: 'proposalStatus',
          title: '状态',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: this.state.proposalStatus,
        },
        {
          dataIndex: 'username',
          title: '创建人',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.setState(
          {
            currentPage: 1,
          },
          () => {
            this.queryTableList();
          },
        );
      },
      onClear: () => {
        //点击重置按钮
        this.addOrder.props.form.resetFields();
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='建议书查询'
        contentHtml={
          <div>
            <div>
              <AdvancedSearch
                {...searchProps}
                onRef={(ref) => {
                  this.addOrder = ref;
                }}
              />
            </div>
            <div style={{ margin: '10px' }}>
              <Checkbox checked={this.state.refreshChecked} onChange={(e) => this.onRefresh(e)}>
                是否自动刷新
              </Checkbox>
            </div>
            {this.showTable()}
            {this.state.detailModalVisible && (
              <ModalC title={'ETF建议书明细'} visible={this.state.detailModalVisible} maskClosable={false} onOk={this.detailOK} onCancel={this.detailCancel} width={1036}>
                <EtfProposalC type={4} proposalType={1} info={this.state.detailData} />
              </ModalC>
            )}
          </div>
        }
      />
    );
  }
}
export default connect(({ tradeSearchM, loading, globalM }) => ({
  tradeSearchM,
  loading,
  globalM,
}))(TradeSearch);
